<template>
    <view  :eventBus="eventBus" :change:eventBus="renderScript.receiveEvent" id="map-container">
    </view>
</template>
 
<script>
  export default {
	data(){
		return {
			eventBus : {},
            searchFn: null
		}
	},
	computed:{
		city (){return this.$store.state.city},
	},
	methods:{
		setCenter (...args) {
			this.eventBus = { name : 'setCenter', args }
		},
		driving (...args) {
			this.eventBus = { name : 'driving', args }
		},
		clearDriving (...args) {
			this.eventBus = { name : 'clearDriving', args }
		},
		search (cb, ...args) {
            this.searchFn = cb;
			this.eventBus = { name : 'search', args, city:this.city }
		},
		searchResult (res) {
            this.searchFn(res);
		},
		setCurrentPosition(position) {
			// 修改 city.center
			this.$store.commit('setCityCenter', `${position.lng},${position.lat}`);
		}
	}
  };
</script>
 
<script module="renderScript" lang="renderjs">
import AMapLoader from '@amap/amap-jsapi-loader';
import { MarkerIcon } from '../plugins/Base64Markers.js';
import gdMapConf from '../config/gdMapConf';

window._AMapSecurityConfig = {
    securityJsCode: gdMapConf.securityJsCode,
}

let AMap = null;
let map = null;
let driving = null;

export default {
    mounted() {
        // AMapLoader.load({
        //     "key": gdMapConf.key,
        //     "version": "2.0",
        //     "plugins": ['AMap.Driving', 'AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geolocation'],
        //     "AMapUI": {
        //         "version": '1.1',
        //         "plugins": ['overlay/SimpleMarker'],
        //     },
        //     "Loca": {
        //         "version": '2.0'
        //     },
        // })
		// 直接使用 window.AMap
			 AMap = window.AMap;
			 map = new AMap.Map('map-container', {
				resizeEnable: true,
				zoom: 13,
				center: gdMapConf.city.center.split(',').map(Number)
			});

            // 定位当前位置
            AMap.plugin('AMap.Geolocation', () => {
                const geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,
                    timeout: 10000,
                    convert: true,
                    showButton: false,
                    panToLocation: true,
                    zoomToAccuracy: true
                });

			geolocation.getCurrentPosition((status, result) => {
				if (status === 'complete' && result.position) {
					map.setCenter(result.position);
				this.$ownerInstance.callMethod('setCurrentPosition', {
					lng: result.position.lng,
					lat: result.position.lat
				});
					console.log('定位成功123123123', result.position); 
				} else {
					console.warn('定位失败，默认北京', result);
				}
			});
            });

    },

    methods: {
        receiveEvent(newParams) {
            let { name, args, city } = newParams || {};
            switch (name) {
                case 'setCenter':
                    this.setMapCenter(...args);
                    break;
                case 'search':
                    this.mapSearch(city, ...args);
                    break;
                case 'driving':
                    this.mapDriving(...args);
                    break;
                case 'clearDriving':
                    this.mapClearDriving(...args);
                    break;
            }
        },

        setMapCenter(lng, lat) {
            if (!map) {
                setTimeout(() => {
                    this.setMapCenter(lng, lat);
                }, 500);
                return;
            }
            map.setCenter([lng, lat]);
        },

        mapSearch(city, str) {
            AMap.plugin(["AMap.PlaceSearch"], () => {
                var placeSearch = new AMap.PlaceSearch({
                    pageSize: 5,
                    pageIndex: 1,
                    city: city.cityCode || city.citycode,
                    citylimit: true,
                });

                placeSearch.search(str, (status, result) => {
                      console.log('搜索结果:', result); // 顺便也可以打印这里，确认有返回
                    if (result.info === 'OK') {
                        this.$ownerInstance.callMethod('searchResult', result.poiList);
                    }
                });
            });
        },

        mapClearDriving() {
            if (driving) {
                driving.clear();
            }
        },

        mapDriving(startLngLat, endLngLat) {
            if (!AMap) {
                setTimeout(() => {
                    this.mapDriving(startLngLat, endLngLat);
                }, 500);
                return;
            }
            if (driving) {
                driving.clear();
            } else {
                driving = new AMap.Driving({ map });
            }

            driving.search(new AMap.LngLat(...startLngLat), new AMap.LngLat(...endLngLat));
        },
    }
};

</script>
 
<style scoped="false">
#map-container {
  width: 100%;
  height: 100%;
}

 .amap-logo,
 .amap-copyright {
  display: none !important;
}

 .amap-info-contentContainer {
  background: #fff;
  border: 2px solid #ddd;
  border-radius: 0.2em;
  padding: 1em;
}
 .amap-info-contentContainer .info {
  display: flex;
  flex-direction: column;
}
 .info__btn {
  margin-top: 4px;
}
#panel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}
</style>
 